//
//  HomeListViewController.m
//  UniversalApp
//
//  Created by 志刚杨 on 2018/1/3.
//  Copyright © 2018年 voidcat. All rights reserved.
//

#import "HomeListViewController.h"
#import "HomeListLogic.h"
#import "PersonModel.h"
#import "XYTransitionProtocol.h"
#import "HomeListCollectionViewCell.h"
#import "SDCycleScrollView.h"
#import "RootWebViewController.h"
#import "UserInfoViewController.h"
#import "CallUserViewController.h"
#import "UserPageInfoModel.h"
#import "OrderIndexViewController.h"
//cell宽度
#define cellWidth KScreenWidth/2-2
#define SDCycleHeight 140
static NSString *isFirstGu2 = @"isFirstGu2";
static NSString *headerViewIdentifier = @"hederview";
@interface HomeListViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,XYTransitionProtocol,HomeListLogicDelegate,SDCycleScrollViewDelegate>
@property(nonatomic, strong) HomeListLogic *logic;//逻辑层
@property(nonatomic, strong) SDCycleScrollView *cycleScrollView;
@property(nonatomic, strong) UILabel *line2;
@property(nonatomic, strong) UIButton *guideBackground;

@end

@implementation HomeListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //    self.isShowLiftBack = NO;//每个根视图需要设置该属性为NO，否则会出现导航栏异常
    
    //初始化逻辑类
    _logic = [HomeListLogic new];
    _logic.page = 1;
    _logic.delegagte = self;
    [_logic loadData];
    [_logic getShuffing];
    [self setupUI];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(getConfigSuccess)
                                                 name:KinitConfigLoginSuccess
                                               object:nil];
    //开始第一次数据拉取
    //    [self.collectionView.mj_header beginRefreshing];
    
}

- (void)getConfigSuccess {
    [[UserManager sharedUserManager] loadUserInfo];
    [_logic loadData];
    [_logic getShuffing];
}

#pragma mark ————— 初始化页面 —————
-(void)setupUI{
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    
    self.collectionView.collectionViewLayout = layout;
    layout.minimumLineSpacing = 1;//设置最小行间距
    layout.minimumInteritemSpacing = 1;//item间距(最小值)
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);//设置section的编距
//    if(curUser.sex == UserGenderUnKnow)
//    {
//        layout.headerReferenceSize=CGSizeMake(self.view.frame.size.width, SDCycleHeight); //设置collectionView头视图的大小
//    }
//    else  if(curUser.sex == UserGenderMale)
//    {
//        layout.headerReferenceSize=CGSizeMake(self.view.frame.size.width, SDCycleHeight + 60); //设置collectionView头视图的大小
//
//    }
//    else  if(curUser.sex == UserGenderFemale)
//    {
        layout.headerReferenceSize=CGSizeMake(self.view.frame.size.width, SDCycleHeight + 60); //设置collectionView头视图的大小
        
//    }
    
    self.collectionView.backgroundColor = CViewBgColor;
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([HomeListCollectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:NSStringFromClass([HomeListCollectionViewCell class])];
    
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerViewIdentifier];
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.view addSubview:self.collectionView];
    
//    if(curUser.sex == UserGenderMale)
//    {
//        BOOL isFirst = [[NSUserDefaults standardUserDefaults] boolForKey:isFirstGu2];
//
//        if (!isFirst) {
//
//            layout.headerReferenceSize=CGSizeMake(self.view.frame.size.width, SDCycleHeight + 120); //设置collectionView头视图的大小
//
//        } else {
//
//            NSLog(@"不是第一次登录");
//        }
//    }

    
}

-(void)addGuideView
{
//    //天机引导页面
//    _guideBackground = [[UIButton alloc] init];
//    [_guideBackground addTarget:self action:@selector(handleguideEvent) forControlEvents:UIControlEventTouchUpInside];
//    UIImageView *guideImage = [[UIImageView alloc] init];
//    guideImage.image = [UIImage imageNamed:@"guide_btn"];
//    [self.view addSubview:_guideBackground];
//    [_guideBackground addSubview:guideImage];
//
//    _guideBackground.backgroundColor = [UIColor clearColor];
//    [_guideBackground mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.edges.equalTo(self.view);
//    }];
//
//    [guideImage mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(@140);
//        make.left.equalTo(@0);
//        make.height.equalTo(@100);
//        make.width.equalTo(self.view);
//    }];
}

-(void)handleguideEvent
{
    _guideBackground.hidden = YES;
}

#pragma mark ————— 下拉刷新 —————
-(void)headerRereshing{
    _logic.page = 1;
    [_logic loadData];
    [_logic getShuffing];
    [self removeNoDataImage];
    
}

#pragma mark ————— 上拉刷新 —————
-(void)footerRereshing{
    _logic.page+=1;
    [_logic loadData];
    [self removeNoDataImage];
}

#pragma mark ————— 数据拉取完成 渲染页面 —————
-(void)requestDataCompleted{
    [self.collectionView.mj_footer endRefreshing];
    [self.collectionView.mj_header endRefreshing];
    
    [UIView performWithoutAnimation:^{
        _line2.text = [NSString stringWithFormat:ASLocalizedString(@"%@人正在接单"),_logic.online_emcee_count];
        
        [self.collectionView reloadData];
    }];
    
}

#pragma mark ————— collection代理方法 —————
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _logic.dataArray.count;
}


-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    HomeListCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([HomeListCollectionViewCell class]) forIndexPath:indexPath];
    if(_logic.dataArray.count == 0)
    {
        
    }
    else
    {
        cell.personModel = _logic.dataArray[indexPath.item];
    }
    return cell;
}

//*******重写的时候需要走一句话
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if(_logic.dataArray.count == 0)
    {
        return;
    }
    UserListInfo *model = _logic.dataArray[indexPath.item];
    UserInfoViewController *vc = [[UserInfoViewController alloc] init];
    vc.uid = model.id;
    [self.navigationController pushViewController:vc animated:YES];
    return;
    //        //标记cell
    //        [self.collectionView setCurrentIndexPath:indexPath];
    //
    //        PersonListCollectionViewCell *cell =(PersonListCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
    //
    //        ProfileViewController *profileVC = [ProfileViewController new];
    //        profileVC.headerImage = cell.imgView.image;
    //        profileVC.isTransition = YES;
    //        [self.navigationController pushViewController:profileVC animated:YES];
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    if (section == 0 )
    {
        return UIEdgeInsetsMake(0, 0, 0, 0);
    }
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

- (CGSize)collectionView:(nonnull UICollectionView *)collectionView layout:(nonnull UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(nonnull NSIndexPath *)indexPath{
    return CGSizeMake(cellWidth,cellWidth);
}

//  返回头视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    //如果是头视图
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        UICollectionReusableView *header=[collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:headerViewIdentifier forIndexPath:indexPath];
        //添加头视图的内容
        [self addContent];
        //头视图添加view
        [header addSubview:self.cycleScrollView];
        
//        if(_line2 == nil)
//        {
            if(curUser.sex == UserGenderMale)
            {
                //一键约 背景
                UIImageView *orderView = [[UIImageView alloc] init];
                orderView.frame = CGRectMake(0, self.cycleScrollView.height + 5, SCREEN_WIDTH, 50);
                orderView.image = [UIImage imageNamed:@"home_order_bg"];
                orderView.userInteractionEnabled = YES;
                //添加手势
                UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGestureRecognizer)];
                [orderView addGestureRecognizer:tapGesture];
                
                //一键约 拨打电话按钮
                UIImageView *orderCall = [[UIImageView alloc] init];
                orderCall.image = [UIImage imageNamed:@"icon_home_call"];
                [orderView addSubview:orderCall];
                
                [header addSubview:orderView];
                
                UILabel *line1 = [[UILabel alloc] init];
                line1.text = ASLocalizedString(@"一键约爱");
                line1.font = DEFAULT_FONT(9);
                line1.textColor = KWhiteColor;
                [header addSubview:line1];
                
                _line2 = [[UILabel alloc] init];
                _line2.text = ASLocalizedString(@"0人正在接单");
                _line2.font = DEFAULT_FONT(9);
                _line2.textColor = KWhiteColor;
                [header addSubview:_line2];
                
                
                [orderCall mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.width.equalTo(@35);
                    make.height.equalTo(@35);
                    make.left.equalTo(@5);
                    make.centerY.equalTo(orderView);
                }];
                
                [line1 mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.left.equalTo(orderCall.mas_right).offset(4);
                    make.top.equalTo(orderCall.mas_top).offset(10);
                }];
                
                [_line2 mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.left.equalTo(orderCall.mas_right).offset(4);
                    make.top.equalTo(line1.mas_bottom).offset(2);
                }];
                _line2.text = [NSString stringWithFormat:ASLocalizedString(@"%@人正在接单"),_logic.online_emcee_count];
                
                
//                BOOL isFirst = [[NSUserDefaults standardUserDefaults] boolForKey:isFirstGu2];
//
//                if (!isFirst) {
//
//                    //=======引导
//                    [_guideBackground removeFromSuperview];
//                    UIImageView *guideImage = [[UIImageView alloc] init];
//                    guideImage.image = [UIImage imageNamed:@"guide_btn"];
//                    [self.view addSubview:_guideBackground];
//                    [_guideBackground addSubview:guideImage];
//
//                    _guideBackground.backgroundColor = [UIColor clearColor];
//                    [_guideBackground mas_makeConstraints:^(MASConstraintMaker *make) {
//                        make.edges.equalTo(self.view);
//                    }];
//
//                    [header addSubview:guideImage];
//
//                    [guideImage mas_makeConstraints:^(MASConstraintMaker *make) {
//                        make.top.equalTo(orderView.mas_bottom).offset(-30);
//                        make.left.equalTo(@0);
//                        make.height.equalTo(@120);
//                        make.width.equalTo(self.view);
//                    }];
//
//
//                } else {
//
//                    NSLog(@"不是第一次登录");
//                }

//        }
        }
        
        
        return header;
    }
    
    
    //如果底部视图
    //    if([kind isEqualToString:UICollectionElementKindSectionFooter]){
    //
    //    }
    return nil;
}

//一键约点击事件
- (void)handleTapGestureRecognizer {
    
    [[NSUserDefaults standardUserDefaults] setBool:@1 forKey:isFirstGu2];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [self.collectionView reloadData];
    [[HUDHelper sharedInstance] syncLoading:@""];
    NSString *url = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"video_call_api" A:@"one_key_video_call"];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    
    [CYNET POSTv3:url parameters:param responseCache:^(id responseObject) {
        
    } success:^(id responseObject) {
        [[HUDHelper sharedInstance] syncStopLoading];
        
        CallUserViewController *callView = [CallUserViewController new];
        callView.usermodel = [UserPageInfoModel modelWithJSON:[[responseObject valueForKey:@"data"] valueForKey:@"to_user_base_info"]];
        callView.channel = [[responseObject valueForKey:@"data"] valueForKey:@"channel_id"];
        callView.iscall = YES;
        [self.navigationController pushViewController:callView animated:NO];
        
        
    } failure:^(NSString *error, NSInteger code) {
        [[HUDHelper sharedInstance] syncStopLoading];
        [MBProgressHUD showTipMessageInWindow:error];
    } hasCache:NO];
}

/*
 *  补充头部内容
 */
-(void)addContent
{
    //    NSArray *imagesURLStrings = @[];
    //
    //    SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, KScreenWidth, SDCycleHeight) delegate:self placeholderImage:[UIImage imageNamed:@"placeholder"]];
    //    cycleScrollView.pageControlStyle = SDCycleScrollViewPageContolStyleClassic;
    //    cycleScrollView.currentPageDotColor = MainColor;
    //    cycleScrollView.imageURLStringsGroup = imagesURLStrings;
    //
    //
    //    self.cycleScrollView = cycleScrollView;
    //    self.cycleScrollView=cycleScrollView;
}

-(void)requestShuffingCompleted:(NSArray *)model
{
    NSMutableArray *imagesURLStrings = [NSMutableArray array];
    
    if(KIOSBASE)
    {
        [imagesURLStrings addObject:[cyurl safeUrl:@"http://pic.qiantucdn.com/58pic/13/29/71/23U58PICasm_1024.jpg!/fw/780/watermark/url/L3dhdGVybWFyay12MS40LnBuZw==/align/center/crop/0x1024a0a0"]];
    }
    else
    {
        for(int i=0; i<model.count; i++)
        {
            ShufflingModel *item = model[i];
            [imagesURLStrings addObject:[cyurl safeUrl:item.image]];
        }
    }
    
    SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, KScreenWidth, SDCycleHeight) delegate:self placeholderImage:[UIImage imageNamed:@"placeholder"]];
    cycleScrollView.pageControlStyle = SDCycleScrollViewPageContolStyleClassic;
    cycleScrollView.currentPageDotColor = MainColor;
    cycleScrollView.imageURLStringsGroup = imagesURLStrings;
    cycleScrollView.bannerImageViewContentMode = UIViewContentModeScaleAspectFill;
    cycleScrollView.autoScrollTimeInterval = 5;
    
    self.cycleScrollView = cycleScrollView;
    self.cycleScrollView=cycleScrollView;
    
    [self.collectionView reloadData];
    
}
#pragma mark ————— 转场动画起始View —————
//-(UIView *)targetTransitionView{
//    NSIndexPath * indexPath = [self.collectionView currentIndexPath];
//    PersonListCollectionViewCell *cell =(PersonListCollectionViewCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
//    return cell.imgView;
//}

-(BOOL)isNeedTransition{
    return YES;
}


-(void)naviBtnClick:(UIButton *)btn{
    DLog(ASLocalizedString(@"点击了筛选按钮"));
}

-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden = YES;
    self.collectionView.frame = CGRectMake(0, 0, KScreenWidth, SCREEN_HEIGHT - TabBarHeight - kTopHeight);
    
}

#pragma mark -  scrollview回调
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{
    
    ShufflingModel *model = _logic.shuffling[index];

    if([model.url isEqualToString:@"#order_page"])
    {
        //判断是否是跳转到排行榜
        OrderIndexViewController *order = [OrderIndexViewController new];
        [self.navigationController pushViewController:order animated:NO];
        return;
    }
    
    model.url = model.url;
    RootWebViewController *web = [[RootWebViewController alloc] initWithUrl:model.url];
    web.isShowCloseBtn  = YES;
    
    RootNavigationController *loginNavi =[[RootNavigationController alloc] initWithRootViewController:web];
    [kRootViewController presentViewController:loginNavi animated:YES completion:nil];
    NSLog(ASLocalizedString(@"点击了第%ld个"),index);
}


#pragma mark -  上下滑动隐藏/显示导航栏

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end

